package vsvm.graphics.charts;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import vsvm.gui.Environment;
import vsvm.gui.VSVMInternalFrame;
import vsvm.math.statistics.histogram.Histogram;

public class GridChart extends VSVMInternalFrame{
	private static final long serialVersionUID = 100L;
	
	public static final int COL_COUNT  = 2;
	public static final int COL_WIDTH  = 200;
	public static final int ROW_HEIGHT = 125;
	
	
	private JScrollPane scrollPane;	
	private int framesCount = 0;
	
	
	public GridChart(ArrayList <AbstractChart> charts, String title)
	{
		super(title);
			
		int chartsCount = charts.size();
		JScrollPane scrollPane = new JScrollPane(); 
		JPanel panel = new JPanel();
		
		int rows = chartsCount/this.COL_COUNT + (chartsCount%this.COL_COUNT != 0 ? 1:0);
		panel.setLayout(new GridLayout(chartsCount/this.COL_COUNT + 
														 (chartsCount%this.COL_COUNT != 0 ? 1:0),
													 	  this.COL_COUNT));
		
		Iterator <AbstractChart> it = charts.iterator();
		while(it.hasNext()) {
			AbstractChart chart = it.next();
			chart.setMinimumSize(new Dimension(COL_WIDTH, ROW_HEIGHT));
			chart.setSize(new Dimension(COL_WIDTH, ROW_HEIGHT));
			chart.addMouseListener(new GridChartMouseListener());
			chart.setToolTipText("Double click to open in new window");
			panel.add(chart);
		}
		
		
		panel.addMouseListener(new GridChartMouseListener());
		scrollPane.getViewport().add(panel);
		
		
		this.getContentPane().add(scrollPane);		
		
	}	
}

class GridChartMouseListener extends MouseAdapter
{
	
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 2) {
			AbstractChart chart = (AbstractChart) e.getComponent();
			
			VSVMInternalFrame frame = new VSVMInternalFrame(chart.getTitle());
			//TODO ka nors normaliau klonavima etc.
			if (chart instanceof HistogramChart)
				chart = new HistogramChart(chart.getTitle(), ((HistogramChart) chart).getHistogram());
			
			frame.getContentPane().add(chart);
			frame.setSize((int)(GridChart.COL_WIDTH*1.5), (int)(GridChart.ROW_HEIGHT*1.5));
			
			Environment.getEnvironment().getMainFrame().addWindow(frame);
			
			frame.setVisible(true);
		}
	}
	
}
